/*
 * Copyright (c) 2009, Servoy-stuff
 * 
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 * 
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 * http://www.fsf.org/licensing/licenses/lgpl.txt
 */

package net.stuff.servoy.beans.calendar;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.swing.SwingConstants;

import com.servoy.j2db.IForm;
import com.servoy.j2db.IFormManager;
import com.servoy.j2db.dataprocessing.IRecord;
import com.servoy.j2db.plugins.IClientPluginAccess;
import com.servoy.j2db.util.Debug;
import com.servoy.j2db.util.Utils;

/**
 * Static helper methods
 * 
 * @version 1.2 - 2010-03-01 - Servoy 5+ version
 * @version 1.0.2 - 2009-06-02 - Added AM/PM support and 12/24 hours
 * @version 1.0.1 - 2009-06-01 - Added Time controls
 * @author servoy-stuff
 * http://www.servoy-stuff.net/
 */
public class DateChooserHelpers {
	
	/**
	 * @param functionName
	 * @return
	 */
	public static boolean isGlobal(String functionName) {
		if (functionName != null) {
			String fName = functionName.trim();
			if (fName.length() > 0) {
				return fName.toLowerCase().startsWith("globals.");
			}
		}
		return false;
	}
	
	/**
	 * Generic helper callback function
	 * 
	 * @param functionName
	 * @param app
	 * @param params
	 */
	public static void runFunctionByName(String functionName, IClientPluginAccess app, Object[] params) {
		if (functionName != null) {
			String fName = functionName.trim();
			if (fName.length() > 0) {
				boolean global = fName.toLowerCase().startsWith("globals.");
				if (global) {
					runGlobalFunctionByName(fName, app, params, true);
				} else {
					runFormFunctionByName(fName, app, params, true);
				}
			}
		}
	}
	
	/**
	 * Generic callback to a "global" Function
	 * @param fName
	 * @param app
	 * @param params
	 */
	private static void runGlobalFunctionByName(String fName, IClientPluginAccess app, Object[] params, boolean async) {
		try {
			fName = fName.substring("globals.".length());
			app.executeMethod(null, fName, params, async);
		} catch (Exception ex) {
			Debug.error(ex);
		}
	}
	
	
	/**
	 * Generic callback to a "form" Function
	 * 
	 * @param fName
	 * @param app
	 * @param params
	 */
	private static void runFormFunctionByName(String fName, IClientPluginAccess app, Object[] params, boolean async) {
		IFormManager manager = app.getFormManager();
		if (manager != null) {
			IForm form = null;
			int indexOfDot = fName.indexOf('.');
			if (indexOfDot > -1) {
				form = manager.getForm(fName.substring(0, indexOfDot));
				fName = fName.substring(indexOfDot+1);
			} else {
				form = manager.getCurrentForm();
			}
			if (form != null) {
				String formName = form.getName();
				if (formName != null) {
					try {
						app.executeMethod(formName, fName, params, async);
					} catch (Exception ex) {
						Debug.error(ex);
					}
				}
			}
		}
	}
	
	/**
	 * @param d1 java.lang.String or java.util.Date
	 * @param d2 java.lang.String or java.util.Date
	 * @param formatter java.text.DateFormat
	 * @return true if both objects are strictly equals (either Date or String)
	 */
	public static boolean equalsDate(Object d1, Object d2, DateFormat formatter) {
		if (d1 == null && d2 != null) return false;
		if (d1 != null && d2 == null) return false;
		if (!Utils.equalObjects(d1, d2)) {
			if (!(d1 instanceof Date) && d2 instanceof Date) return false;
			if (d1 instanceof Date && !(d2 instanceof Date)) return false;
			
			String ds1 = formatter.format(d1);
			String ds2 = formatter.format(d2);
			return ds1.equals(ds2);
		}
		return true;
	}
	
	/**
	 * @param paramInt
	 * @return the style horizontal-alignment CSS String depending on the SwingConstants
	 */
	public static String getWicketHorizontalAlignment(int paramInt) {
		String paramString = "left";
		switch(paramInt) {
			case SwingConstants.CENTER:
				paramString = "center";
				break;
			case SwingConstants.RIGHT:
				paramString = "right";
		}
		return paramString;
	}
	
	/**
	 * Test a String
	 * @return true if the passed String is not empty
	 */
	public static boolean isNotEmpty(String s) {
		return !isEmpty(s);
	}
	
	/**
	 * Test a String
	 * @return true if the passed String is empty
	 */
	public static boolean isEmpty(String s) {
		return (s == null || s.trim().length() == 0);
	}

	/**
	 * Test method for the presence of the dataprovider in the record, 
	 * could be enhanced with search for related foundset
	 * @param record the currentRecord
	 * @param dataProviderID the dataProviderID
	 * @return true id the dataProvider exists in the current FoundSet
	 */
	public static boolean isContainedInFoundset(IRecord record, String dataProviderID) {
		boolean isContained = false;
		if (record != null && isNotEmpty(dataProviderID)) {
			try {
				record.getValue(dataProviderID);
				isContained = true;
			} catch (Exception ex) {
				Debug.error(ex);
			}
		}
		return isContained;
	}
	
	/**
	 * @param pattern
	 * @return true if the pattern contains hours related information
	 */
	public static boolean containHours(String pattern) {
		return (pattern != null && (pattern.toLowerCase().contains("h") || pattern.toLowerCase().contains("k")));
	}
	
	/**
	 * @param pattern
	 * @return true if the pattern contains 2 digit hours related information
	 */
	public static boolean useTwoDigitHours(String pattern) {
		return (pattern != null && (pattern.toLowerCase().contains("hh") || pattern.toLowerCase().contains("kk")));
	}
	
	/**
	 * @param pattern
	 * @return true if the pattern uses AM/PM hours
	 */
	public static boolean hoursStartsWithOne(String pattern) {
		return (pattern != null && (pattern.contains("k") || (pattern.contains("h"))));
	}
	
	/**
	 * @param pattern
	 * @return true if the pattern uses AM/PM hours
	 */
	public static boolean useAmPm(String pattern) {
		return (pattern != null && (pattern.contains("K") || (pattern.contains("h"))));
	}
	
	/**
	 * @param pattern
	 * @return true if the pattern contains minutes related information
	 */
	public static boolean containMinutes(String pattern) {
		return (pattern != null && pattern.contains("m"));
	}
	
	/**
	 * @param pattern
	 * @return true if the pattern contains 2 digit minutes related information
	 */
	public static boolean useTwoDigitMinutes(String pattern) {
		return (pattern != null && pattern.contains("mm"));
	}
	
	/**
	 * @param pattern
	 * @return true if the pattern contains seconds related information
	 */
	public static boolean containSeconds(String pattern) {
		return (pattern != null && pattern.contains("s"));
	}
	
	/**
	 * @param pattern
	 * @return true if the pattern contains 2 digit seconds related information
	 */
	public static boolean useTwoDigitSeconds(String pattern) {
		return (pattern != null && pattern.contains("ss"));
	}
	
	public static boolean useTime(String pattern) {
		return (pattern!= null && (containHours(pattern) || containMinutes(pattern) || containSeconds(pattern)));
	}
	
	public static Date resetDate(Date date) {
		if (date != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.set(Calendar.AM_PM, Calendar.AM);
			cal.set(Calendar.HOUR, 0);
			cal.set(Calendar.MINUTE, 0);
			cal.set(Calendar.SECOND, 0);
			cal.set(Calendar.MILLISECOND, 0);
			date = cal.getTime();
		}
		return date;
	}
}
